package com.pms.web;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.cache.utils.RedisCacheUtil;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.service.*;
import com.pms.util.DaHaoLockUtil;
import com.pms.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
/**
 * 1）只支持 excel表格添加
 * 2）卡号添加后 无法修改，无法删除
 */
@RestController
@RequestMapping("estateDoorCardBase")
@Api(value="发卡",description = "发卡管理界面接口")
public class EstateDoorCardController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IEstateUnitCardService estateUnitCardService;
    @Autowired
    IEstateDoorCardService estateDoorCardService;
    @Autowired
    IEstateLockCardService estateLockCardService;
    @Autowired
    private IEstateAgencyService agencyService;
    @Autowired
    private IUnitBuildingService unitBuildingService;
    @Autowired
    private IEstateEqFactoryService estateEqFactoryService;
    @Autowired
    private DaHaoLockUtil daHaoLockUtil;
    @Autowired
    private IEntranceDoorService entranceDoorService;
    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @ApiOperation(value = "分页查询发卡记录")
    @RequestMapping(value = "/readPage",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageSize",value="请求条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageNum",value="请求页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="communityId",value="社区id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="unitId",value="单元id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="doorId",value="门id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="cardNum",value="卡号",required = false,dataType = "string",paramType="form"),
    })
    public R readPage(Integer pageSize,Integer pageNum,Long communityId,Long unitId,Long doorId,String cardNum){
        parameterIsNull(communityId,"社区id不能为空");
        if(null==pageNum||pageNum<1){pageNum=1;}
        if(null==pageSize||pageSize<1){pageSize=10;}
        Page<EstateDoorCard> page = new Page<EstateDoorCard>(pageNum,pageSize);
        Wrapper<EstateDoorCard> wp = new EntityWrapper<EstateDoorCard>();
        if(null!=communityId){
            wp.eq("community_id",communityId);
        }
        if(null!=unitId){
            wp.eq("unit_id",unitId);
        }
        if(null!=doorId){
            wp.eq("door_id",doorId);
        }
        if(StringUtils.isNotBlank(cardNum)){
            wp.like("cardNumTen",cardNum);
        }
        Page<EstateDoorCard> returnPage = estateDoorCardService.selectPage(page,wp);
        return R.ok().put("data",returnPage).putMpPageDescription().putDescription(EstateDoorCard.class);
    }


//    @ApiOperation(value = "远程发卡-每次下发10张")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="doorId",value="门id",required = false,dataType = "long",paramType="form"),
//            @ApiImplicitParam(name="unitId",value="单元id",required = false,dataType = "long",paramType="form"),
//            @ApiImplicitParam(name = "validTime", value = "有效期时间,默认100年(yyyyMMddHHmmss)", required = false, dataType = "string", paramType = "form"),
//    })
//    @RequestMapping(value = "/remoteSendCardToLock",method =RequestMethod.POST)
    public R remoteSendCardToLock(Long unitId,Long doorId,String validTime){
        parameterIsNull(unitId,"请选择单元");
        parameterIsNull(doorId,"请选择门");
        Date validDate = null;
        Date nowDate = new Date();
        if (StringUtils.isBlank(validTime)) {
            validDate = DateUtil.addDate(nowDate, 1, 100);//获取当前时间 加上 100年
        }
        if (StringUtils.isNotBlank(validTime)) {
            validDate = DateUtil.stringToDate(validTime);
            if (validDate == null) {
                return R.error(400, "有效期时间格式错误");
            }
            if (DateUtil.getDayBetween(new Date(), validDate) < 2) {// 当前时间 和 有效时间 间隔天数小于1天
                return R.error(400, "有效期时间必须在2天以上");
            }
        }
        EntranceDoor door = entranceDoorService.selectById(doorId);
        parameterIsNull(door, "未查询到门信息");
        if(door.getDoorType()!=1){
            if(!door.getUnitId().equals(unitId)){
                return R.error(400,"门信息与单元信息匹配出错");
            }
        }
        if(door.getDoorType()==1){
            UnitBuilding unit =unitBuildingService.selectById(unitId);
            if(!door.getCommunityId().equals( unit.getCommunityId() )){
                return R.error(400,"门信息与单元信息匹配出错");
            }
        }
        /*==验证设备==*/
        Map<String,Object> lockMap = daHaoLockUtil.checkDeviceIsOnLine(null,doorId);
        if(lockMap==null){
            return  R.error(400,"门尚未绑定设备");
        }
        if(lockMap.get("isOnLine").toString().equals("false")){
            return  R.error(400,"设备不在线");
        }
        List<EstateLockCard> lockCardList = (List<EstateLockCard>) redisCacheUtil.getVlue("estateLockCard:selectListByEqSn:"+lockMap.get("eqSn").toString().trim());
        if(lockCardList==null||lockCardList.isEmpty()){
            lockCardList = estateLockCardService.selectListByEqSn(lockMap.get("eqSn").toString().trim());
        }
        if(lockCardList!=null&&!lockCardList.isEmpty()){
            redisCacheUtil.saveAndUpdate("estateLockCard:selectListByEqSn:"+lockMap.get("eqSn").toString().trim(),lockCardList,10);
            daHaoLockUtil.sendTenCard(lockMap.get("eqSn").toString(),true);
            return  R.error(400,"该门尚有卡片正在下发");
        }
        /*==查询卡片==*/
        String leftJoinWhere = "";
        Wrapper<EstateUnitCard> unitCardListWp = new EntityWrapper<EstateUnitCard>();
        unitCardListWp.eq("euc.community_id", door.getCommunityId());
        if (unitId != null) {
            unitCardListWp.eq("euc.unit_id", unitId);
        }
        if (null != doorId) {
            leftJoinWhere = " and edc.door_id = "+doorId;
        }
        unitCardListWp.and("edc.door_card_id is null");
        unitCardListWp.orderBy("euc.create_time",true);//根据录入时间升序查询
        List<EstateUnitCard> unitCardList = estateDoorCardService.selectWillUseCardList(leftJoinWhere,unitCardListWp);
        if(unitCardList==null||unitCardList.isEmpty()){
            return R.error(400, "暂无卡片下发");
        }
        List<EstateLockCard> lockCards = new ArrayList<EstateLockCard>();
        for(int x=0;x<unitCardList.size();x++){
            EstateLockCard lockCard = new EstateLockCard();
            lockCard.setCardNumSixteen(unitCardList.get(x).getCardNumSixteen());
            lockCard.setCardNumTen(unitCardList.get(x).getCardNumTen());
            lockCard.setCommunityId(unitCardList.get(x).getCommunityId());
            lockCard.setCommunityName(unitCardList.get(x).getCommunityName());
            lockCard.setDoorId(door.getDoorId());
            lockCard.setDoorName(door.getDoorName());
            lockCard.setEqPswd(lockMap.get("eqPswd").toString());
            lockCard.setEqSn(lockMap.get("eqSn").toString());
            lockCard.setUnitId(unitCardList.get(x).getUnitId());
            lockCard.setUnitName(unitCardList.get(x).getUnitName());
            lockCard.setValidTime(validDate);
            lockCards.add(lockCard);
        }
        estateLockCardService.insertBatch(lockCards);
        redisCacheUtil.saveAndUpdate("estateLockCard:selectListByEqSn:"+lockMap.get("eqSn").toString().trim(),lockCards,10);
        daHaoLockUtil.sendTenCard(lockMap.get("eqSn").toString(),true);
        return R.ok();
    }

    @ApiOperation(value = "远程发卡-每次下发500张")
    @RequestMapping(value = "/remoteSendFiveHundredCardToLock",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="doorId",value="门id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="unitId",value="单元id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="sendCardNum",value="本次发卡数量(最多500,默认500)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name = "validTime", value = "有效期时间,默认10年(yyyyMMddHHmmss)", required = false, dataType = "string", paramType = "form"),
    })
    public R remoteSendFiveHundredCardToLock(Long unitId,Long doorId,String validTime,Integer sendCardNum){
        parameterIsNull(unitId,"请选择单元");
        parameterIsNull(doorId,"请选择门");
        if(sendCardNum==null||sendCardNum<1||sendCardNum>500){
            sendCardNum =500;
        }
        Date validDate = null;
        Date nowDate = new Date();
        if (StringUtils.isBlank(validTime)) {
            validDate = DateUtil.addDate(nowDate, 1, 10);//获取当前时间 加上 100年
        }
        if (StringUtils.isNotBlank(validTime)) {
            validDate = DateUtil.stringToDate(validTime);
            if (validDate == null) {
                return R.error(400, "有效期时间格式错误");
            }
            if (DateUtil.getDayBetween(new Date(), validDate) < 2) {// 当前时间 和 有效时间 间隔天数小于1天
                return R.error(400, "有效期时间必须在2天以上");
            }
        }
        EntranceDoor door = entranceDoorService.selectById(doorId);
        parameterIsNull(door, "未查询到门信息");
        if(door.getDoorType()!=1){
            if(!door.getUnitId().equals(unitId)){
                return R.error(400,"门信息与单元信息匹配出错");
            }
        }
        if(door.getDoorType()==1){
            UnitBuilding unit =unitBuildingService.selectById(unitId);
            if(!door.getCommunityId().equals( unit.getCommunityId() )){
                return R.error(400,"门信息与单元信息匹配出错");
            }
        }
        /*==验证设备==*/
        Map<String,Object> lockMap = daHaoLockUtil.checkDeviceIsOnLine(null,doorId);
        if(lockMap==null){
            return  R.error(400,"门尚未绑定设备");
        }
        if(lockMap.get("isOnLine").toString().equals("false")){
            return  R.error(400,"设备不在线");
        }
        List<EstateLockCard> lockCardList = estateLockCardService.selectListByEqSn(lockMap.get("eqSn").toString().trim());
        if(lockCardList!=null&&!lockCardList.isEmpty()){
           daHaoLockUtil.sendFiveHundredCard(lockMap,lockCardList);
           return  R.error(400,"上一批卡片尚未下发完成,正在下发");
        }else{
             /*==查询卡片==*/
           String leftJoinWhere ="";
            Wrapper<EstateUnitCard> unitCardListWp = new EntityWrapper<EstateUnitCard>();
            unitCardListWp.eq("euc.community_id", door.getCommunityId());
            if (unitId != null) {
                unitCardListWp.eq("euc.unit_id", unitId);
            }
            if (null != doorId) {
//                unitCardListWp.eq("edc.door_id", doorId);
                leftJoinWhere= " and edc.door_id = "+doorId;
            }
            unitCardListWp.and("edc.door_card_id is null");
            unitCardListWp.orderBy("euc.create_time",true);//根据录入时间升序查询
            unitCardListWp.last(" LIMIT "+sendCardNum);
            List<EstateUnitCard> unitCardList = estateDoorCardService.selectWillUseCardList(leftJoinWhere,unitCardListWp);
            if(unitCardList==null||unitCardList.isEmpty()){
                return R.error(400, "暂无卡片可以下发,请先录入卡片");
            }
            List<EstateLockCard> lockCards = new ArrayList<EstateLockCard>();
            for(int x=0;x<unitCardList.size();x++){
                EstateLockCard lockCard = new EstateLockCard();
                lockCard.setCardNumSixteen(unitCardList.get(x).getCardNumSixteen());
                lockCard.setCardNumTen(unitCardList.get(x).getCardNumTen());
                lockCard.setCommunityId(unitCardList.get(x).getCommunityId());
                lockCard.setCommunityName(unitCardList.get(x).getCommunityName());
                lockCard.setDoorId(door.getDoorId());
                lockCard.setDoorName(door.getDoorName());
                lockCard.setEqPswd(lockMap.get("eqPswd").toString());
                lockCard.setEqSn(lockMap.get("eqSn").toString());
                lockCard.setUnitId(unitCardList.get(x).getUnitId());
                lockCard.setUnitName(unitCardList.get(x).getUnitName());
                lockCard.setValidTime(validDate);
                lockCards.add(lockCard);
            }
            estateLockCardService.insertBatch(lockCards);
            daHaoLockUtil.sendFiveHundredCard(lockMap,lockCards);
        }
        return R.ok("卡片下发中");
    }

}